package org.jsola.hr.web;

import org.apache.commons.io.FilenameUtils;
import org.jsola.core.Page;
import org.jsola.core.Result;
import org.jsola.exception.ParamException;
import org.jsola.hr.constant.HrConstants;
import org.jsola.hr.dto.SaleUserAddDTO;
import org.jsola.hr.dto.SaleUserUpdateDTO;
import org.jsola.hr.dto.permission.HrGroupAddDTO;
import org.jsola.hr.dto.permission.HrGroupUpdateDTO;
import org.jsola.hr.entity.SaleUserDO;
import org.jsola.hr.query.SaleUserQuery;
import org.jsola.hr.service.ISaleUserService;
import org.jsola.hr.vo.HrGroupListVO;
import org.jsola.hr.vo.SaleUserListVO;
import org.jsola.hr.vo.SaleUserVO;
import org.jsola.permission.vo.GroupListVO;
import org.jsola.permission.vo.GroupVO;
import org.jsola.user.core.TokenUser;
import org.jsola.user.core.UserContext;
import org.jsola.user.entity.UserDO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;
import java.util.List;
import javax.validation.Valid;


/**
 * 销售人员
 *
 * @author zhr
 */
@RestController("hrSaleUserController")
@RequestMapping(HrConstants.API_PATH + "/v1/saleUsers")
public class SaleUserController implements ISaleUserControllerAPI {

    @Autowired
    private ISaleUserService saleUserService;

    @Override
    @PostMapping
    public Result<SaleUserVO> save(@Valid @RequestBody SaleUserAddDTO saleUserAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 新增销售人员权限校验

        return Result.success(
                saleUserService.save(saleUserAddDTO, tokenUser)
        );
    }


    @Override
    @PutMapping
    public Result<Integer> update(@Valid @RequestBody SaleUserUpdateDTO saleUserUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 修改销售人员权限校验

        int count = saleUserService.update(saleUserUpdateDTO, tokenUser);
        if (count == 0) {
            throw new ParamException("更新失败，请刷新页面后重试");
        }
        return Result.success(count);
    }


    @Override
    @DeleteMapping(value = "/{saleUserId}")
    public Result<Integer> delete(@PathVariable String saleUserId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 彻底删除销售人员权限校验

        int count = saleUserService.deleteByIds(tokenUser, saleUserId);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @DeleteMapping
    public Result<Integer> deleteBatch(@RequestBody String[] saleUserIds) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 批量彻底删除销售人员权限校验

        int count = saleUserService.deleteByIds(tokenUser, saleUserIds);
        if (count == 0) {
            throw new ParamException("删除失败，请刷新页面后重试");
        }
        return Result.success(count);
    }

    @Override
    @GetMapping(value = "/{saleUserId}")
    public Result<SaleUserVO> findById(@PathVariable String saleUserId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看销售人员权限校验

        return Result.success(
                saleUserService.selectById(saleUserId, tokenUser.getSiteId())
        );
    }

    @Override
    @GetMapping(value = "/listAll")
    public Result<List<SaleUserListVO>> listAll(@Valid SaleUserQuery saleUserQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看销售人员权限校验

        return Result.success(
                saleUserService.select(saleUserQuery, tokenUser.getSiteId())
        );
    }


    @Override
    @GetMapping
    public Result<Page<SaleUserListVO>> page(@Valid SaleUserQuery saleUserQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.selectPage(saleUserQuery, tokenUser)
        );
    }

    @GetMapping("/selectGroupTree")
    public Result<List<GroupListVO>> selectGroupTree(@Valid SaleUserQuery saleUserQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.selectGroupTree(saleUserQuery.getGroupOrAdminName(), tokenUser)
        );
    }

    @GetMapping("/selectAdminByGroupId/{groupId}")
    public Result<List<UserDO>> selectAdminByGroupId(@PathVariable String groupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.selectAdminByGroupId(groupId)
        );
    }

    @GetMapping("/selectSaleByGroupId")
    public Result<Page<SaleUserListVO>> selectSaleByGroupId(@Valid SaleUserQuery saleUserQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.selectSaleByGroupId(saleUserQuery, tokenUser)
        );
    }

    @GetMapping("/exportSale")
    public ResponseEntity<Resource> exportSale(@Valid SaleUserQuery saleUserQuery) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        String excelFilePath = saleUserService.exportSale(saleUserQuery, tokenUser);
        // 编码文件名，防止乱码
        String filenames = new String(FilenameUtils.getName(excelFilePath).getBytes(StandardCharsets.UTF_8), StandardCharsets.ISO_8859_1);
        return ResponseEntity.ok()
                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=\"" + filenames + "\"")
                .header(HttpHeaders.CONTENT_TYPE, "application/vnd.ms-excel")
                .body(new FileSystemResource(excelFilePath));
    }

    @GetMapping("/selectSaleBySite")
    public Result<List<SaleUserDO>> selectSaleBySite() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.selectSaleBySite(tokenUser)
        );
    }

    @PostMapping("/saveGroup")
    public Result<GroupVO> saveGroup(@RequestBody HrGroupAddDTO hrGroupAddDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        return Result.success(
                saleUserService.saveGroup(hrGroupAddDTO, tokenUser)
        );
    }

    @PutMapping("/updateGroup")
    public Result<String> updateGroup(@RequestBody HrGroupUpdateDTO hrGroupUpdateDTO) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        saleUserService.updateGroup(hrGroupUpdateDTO, tokenUser);
        return Result.success();
    }

    @DeleteMapping("/deleteGroup/{groupId}")
    public Result<String> deleteGroup(@PathVariable String groupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验

        saleUserService.deleteGroup(groupId, tokenUser);
        return Result.success();
    }

    @GetMapping("/selectGroupInfo/{groupId}")
    public Result<HrGroupListVO> selectGroupInfo(@PathVariable String groupId) {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验


        return Result.success(
                saleUserService.selectGroupInfo(groupId, tokenUser)
        );
    }

    @GetMapping("/selectDefaultGroupId")
    public Result<GroupListVO> selectDefaultGroupId() {
        TokenUser tokenUser = UserContext.getUser();
        // todo 查看项目权限校验


        return Result.success(
                saleUserService.selectDefaultGroupId(tokenUser)
        );
    }
}

